package com.Servlet;

import com.Bean.User;
import com.Util.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;

@WebServlet(urlPatterns = {"/login"})
public class login extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {


        System.out.println(res.isCommitted());
        try {
            if (req.getSession().getAttribute("username") != null) {
                req.getRequestDispatcher("/serve/myvps.jsp").forward(req, res);
            } else {
                User user = UserDao.getUser(req.getParameter("username"), req.getParameter("passwd"));

                HttpSession session = req.getSession(true);

                if (user != null) {

                    Map<String, String> message = new LinkedHashMap<String, String>();
                    message.put("用户名", user.getUsername());
                    message.put("姓", user.getFamilyname());
                    message.put("名", user.getName());
                    message.put("邮箱", user.getEmail());

                    if (req.getParameter("net_auto_login") != null)
                        session.setMaxInactiveInterval(7 * 24 * 60 * 60);
                    session.setAttribute("Login", message);
                    session.setAttribute("username", user.getUsername());
                    res.sendRedirect("./serve/myvps.jsp");
                } else {
                    session.setAttribute("message", "密码错误");
                    res.sendRedirect("./error/login.jsp");

                }

            }
        } catch (ServletException e) {
            e.printStackTrace();
        }
    }

    protected void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException {
        doGet(req, res);
    }
}
